<script setup name="Home">
import { ref, onMounted, computed } from "vue";
import { useRoute } from "vue-router";
import StudyBar from "../components/StudyBar.vue";
import DisplayerArea from "../components/DisplayerArea.vue";
import SystemInfo from "../components/SystemInfo.vue";
import Toolbar from "../components/Toolbar.vue";
import { useArchiveStore } from "../stores/archive";

import initCornerstone3D from "../cornerstone3D";

const archiveStore = useArchiveStore();

const route = useRoute();
const view2d = ref(null);
const navbarHW = ref(146);
const toolbarHW = ref(300);
const toolbarPos = ref("right"); // top or right
const navbarPos = ref("bottom"); // bottom or left

const mainClass = computed(() => {
	const vorh = toolbarPos.value === "top" ? "vertical" : "horizontal-reverse";
	return "flex-" + vorh;
});

const tbResizerClass = computed(() => {
	const vorh = toolbarPos.value === "top" ? "horizontal" : "vertical";
	return "resizer-" + vorh;
});

const toolbarClass = computed(() => {
	return "toolbar-" + toolbarPos.value;
});

const toolbarStyle = computed(() => {
	if (toolbarPos.value === "top") {
		return {
			height: toolbarHW.value + "px"
		};
	} else {
		return {
			width: toolbarHW.value + "px"
		};
	}
});

const navDisplayClass = computed(() => {
	const vorh = navbarPos.value === "bottom" ? "vertical-reverse" : "horizontal";
	return "flex-" + vorh;
});

const navResizerClass = computed(() => {
	const vorh = navbarPos.value === "bottom" ? "horizontal" : "vertical";
	return "resizer-" + vorh;
});

const navClass = computed(() => {
	return "nav-" + navbarPos.value;
});

const navbarStyle = computed(() => {
	if (navbarPos.value === "bottom") {
		return {
			height: navbarHW.value + "px"
		};
	} else {
		return {
			width: navbarHW.value + "px"
		};
	}
});

function resizeNavbar(e) {
	e.stopPropagation();
	// console.log("resizeNavbar", e.target);
	// const spliter = e.target;
	view2d.value.style.cursor = navbarPos.value === "bottom" ? "ns-resize" : "ew-resize";
	view2d.value.onmousemove = function (e) {
		// console.log("onmousemove", e.movementX, e.movementY);
		let delta = navbarPos.value === "bottom" ? -e.movementY : e.movementX;
		const value = navbarHW.value + delta;

		if (value < 146 || value > 220) return;
		navbarHW.value = value;
		// console.log("navbarHW:", navbarHW.value);
	};

	document.onmouseup = function () {
		// console.log("mouseup");
		view2d.value.onmousemove = null;
		document.onmouseup = null;
		view2d.value.style.cursor = "";
	};
}

function resizeToolbar(e) {
	e.stopPropagation();
	view2d.value.style.cursor = toolbarPos.value === "top" ? "ns-resize" : "ew-resize";
	view2d.value.onmousemove = function (e) {
		// const w = toolbarW.value - e.movementX;
		// let delta = toolbarPos.value === "top" ? e.movementY : -e.movementX;
		let delta, minVal, maxVal;
		if (toolbarPos.value === "top") {
			delta = e.movementY;
			minVal = 146;
			maxVal = 220;
		} else {
			delta = -e.movementX;
			minVal = 110;
			maxVal = 520;
		}

		const value = toolbarHW.value + delta;
		if (value < minVal || value > maxVal) return;
		toolbarHW.value = value;
	};

	document.onmouseup = function () {
		// console.log("mouseup");
		view2d.value.onmousemove = null;
		document.onmouseup = null;
		view2d.value.style.cursor = "";
	};
}

const toggleNavbarPos = () => {
	navbarPos.value = navbarPos.value === "bottom" ? "right" : "bottom";
};

const toggleToolbarPos = () => {
	toolbarPos.value = toolbarPos.value === "top" ? "right" : "top";
	toolbarHW.value = toolbarPos.value === "top" ? 146 : 220;
};

async function OnToolbarAction(action) {
	// console.log("OnToolbarAction", action);
	if (action.name === "changeToolbarPos") {
		toggleToolbarPos();
	}
	if (action.name === "changeNavPos") {
		toggleNavbarPos();
	}
	if (action.name === "openFolder") {
		console.log("openFolder");
		// const imageId =
		// 	"dicomweb:http://192.168.10.30:9000/storage2/CT/2016-10-11/2/56170797503c22cc1873bed3c5d2a8d5/97b9ff0be7d8e50472932f33a539b9b3/8606190eaeab5c4036be8c71863992cb.dcm?params=dXVnbGpmTUlyaWw3ZXhqWndTU3BWR3ZYTXN0UXNxYWFXOHpyQ1NNeTRSMD0=";

		const fileHandles = await openFolder();
		// const dcmfiles = fileHandles.filter(file => file.name.endsWith(".dcm"));
		console.log("openFolder, fileHandles:", fileHandles);
		if (Array.isArray(fileHandles)) {
			fileHandles.forEach(async fileHandle => {
				const file = await fileHandle.getFile();
				await archiveStore.archiveFile(file);
			});

			console.log("openFolder, archiveData:", archiveStore.archiveData);
		} else {
			console.error("openFolder, fileHandles is not an array");
		}
		// openFolder().then(async files => {
		// 	// console.log("openFolder, files:", files);
		// 	// console.log("openFolder, archiveData:", archiveStore.archiveData);
		// 	// 解析文件
		// 	const file = await files[0].getFile();
		// 	archiveStore.archiveFile(file);
		// });
	}
	if (action.name === "openFile") {
		console.log("openFile, files:", action.files);
		const file = action.files[0];
		archiveStore.archiveFile(file);
	}
}

async function openFolder() {
	return new Promise(async (resolve, reject) => {
		try {
			// 请求用户选择一个文件夹
			const handle = await showDirectoryPicker();
			const fileHandles = [];
			await processHandle(handle, fileHandles);
			// console.log("handle2:", fileHandles);
			resolve(fileHandles);
			// 显示图像
		} catch (err) {
			// console.error("无法打开文件夹:", err);
			reject(err);
		}
	});
}

async function processHandle(handle, fileHandles) {
	if (handle.kind === "file") {
		return;
	}
	// handle.children = [];
	const itr = await handle.entries();
	for await (const entry of itr) {
		// console.log("entry:", entry);
		if (entry[1].kind === "file" && entry[1].name.endsWith(".dcm")) {
			fileHandles.push(entry[1]);
		} else {
			await processHandle(entry[1], fileHandles);
		}
		// handle.children.push(entry[1]);
	}
}

onMounted(() => {
	console.log("Home mounted, studyId:", route.params.studyId);
	initCornerstone3D();
});
</script>

<template>
	<div class="container flex-vertical" ref="view2d">
		<div class="header flex-horizontal">
			<div class="logo">
				<SystemInfo />
			</div>
			<div class="study-list">
				<StudyBar />
			</div>
		</div>
		<div class="main" :class="mainClass">
			<div :class="toolbarClass" :style="toolbarStyle">
				<Toolbar @action="OnToolbarAction" />
			</div>
			<div :class="tbResizerClass" @mousedown="resizeToolbar"></div>
			<div class="nav-display" :class="navDisplayClass">
				<div :class="navClass" :style="navbarStyle">Series List</div>
				<div :class="navResizerClass" @mousedown="resizeNavbar"></div>
				<div class="display-area">
					<DisplayerArea />
				</div>
			</div>
		</div>
		<div class="footer">Statusbar</div>
	</div>
</template>

<style scoped lang="scss">
$bg-color: #333;
$main-color: lightblue;
// $header-color: #108ee9;
$header-color: #ffff;
$footer-color: #ffff;
$resizer-width: 2px;
$header-height: 100px;
$footer-height: 34px;

.container {
	background-color: $bg-color;
	height: 100vh;
	width: 100vw;
	max-width: 100%;
	max-height: 100%;
	justify-content: center;
	// align-items: center;
	text-align: center;
	color: white;
	user-select: none;
}

.flex-vertical {
	display: flex;
	flex-direction: column;
}

.flex-vertical-reverse {
	display: flex;
	flex-direction: column-reverse;
}

.flex-horizontal {
	display: flex;
	flex-direction: row;
}

.flex-horizontal-reverse {
	display: flex;
	flex-direction: row-reverse;
}

.resizer-vertical {
	cursor: ew-resize;
	width: $resizer-width;
	background-color: gray;
	z-index: 10;
}

.resizer-horizontal {
	cursor: ns-resize;
	height: $resizer-width;
	background-color: gray;
	width: 100%;
	z-index: 10;
}

.header {
	height: $header-height;
	background-color: $header-color;
	border-bottom: gray solid 1px;

	.logo {
		height: 100%;
		width: 200px;
		border-right: gray solid 1px;
		flex-shrink: 0;
	}

	.study-list {
		flex: 1;
		height: 100%;
		// background-color: lightblue;
	}
}

.main {
	width: 100%;
	height: calc(100vh - $header-height - $footer-height);
	background-color: $main-color;

	.nav-display {
		flex: 1;
	}

	.toolbar-top {
		height: 200px;
		width: 100%;
	}

	.toolbar-right {
		width: 200px;
		height: 100%;
	}

	.nav-display {
		.display-area {
			flex: 1;
			flex-shrink: 0;
		}
		.nav-left {
			height: 100%;
		}

		.nav-bottom {
			width: 100%;
		}
	}
}

.footer {
	background-color: $footer-color;
	height: $footer-height;
	border-top: gray solid 1px;
}
</style>
